﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZP.Common;
using ZP.DTO.Common;
using ZP.DTO.fz_base_employee;
using ZP.DTO.fz_sys_user;
using ZP.IBLL;
using ZP.IDAL;
using ZP.Model;
using static ZP.DTO.Common.UserLoginDTO;
using System.IO;
using ZP.DTO.fz_sys_role;
using System.Data.Entity.Validation;
using Z.EntityFramework.Plus;

namespace ZP.BLL
{
    public partial class fz_sys_userService : BaseService<fz_sys_user, int>, Ifz_sys_userService
    {
        //public fz_sys_userService(Ifz_sys_userDAL _fz_sys_userDAL, Ifz_sys_menuDAL _fz_sys_menuDAL, Ifz_sys_roleDAL _fz_sys_roleDAL, Ifz_base_employeeDAL _fz_base_employeeDAL)
        //{
        //    this._fz_sys_userDAL = _fz_sys_userDAL;
        //    this._fz_sys_menuDAL = _fz_sys_menuDAL;
        //    this._fz_sys_roleDAL = _fz_sys_roleDAL;
        //    this._fz_base_employeeDAL = _fz_base_employeeDAL;

        //    this._repository = _fz_sys_userDAL;
        //}

        #region 用户管理

        /// <summary>
        /// 查询所有用户信息(含模糊查询)分页
        /// </summary>
        /// <returns></returns>
        public PageModel<fz_sys_userResultDTO> GetSysUser(fz_sys_userSearchDTO dto)
        {
            PageModel<fz_sys_userResultDTO> result = new PageModel<fz_sys_userResultDTO>();
            var psie = (ZPJ_Entities)_repository.GetDbContext();

            var iquery = from u in psie.fz_sys_user
                         join e in psie.fz_base_employee on u.employeeId equals (int)e.id
                         where u.state == ZPFlagType.YES
                         orderby u.id
                         select new fz_sys_userResultDTO
                         {
                             id = u.id,
                             account = u.account,
                             password = u.password,
                             roleId = u.roleId,
                             roleName = u.roleName,
                             employeeId = u.employeeId,
                             state = u.state,
                             isLocked = u.isLocked,
                             lockTime = u.lockTime,
                             updater = u.updater,
                             updatetime = u.updatetime,
                             headImg = u.headImg,
                             errorTimes = u.errorTimes,
                             lastErrorTime = u.lastErrorTime,
                             employeeName = e.name,
                             employeeCode = e.code,
                         };

            if (null != dto)
            {
                if (!string.IsNullOrWhiteSpace(dto.SearchText))
                {
                    iquery = iquery.Where(p => p.account.Contains(dto.SearchText) ||
                        p.roleName.Contains(dto.SearchText)
                    );
                }
            }
            result.count = iquery.Count();
            iquery = iquery.OrderBy(m => m.id).Skip((dto.page - 1) * dto.limit).Take(dto.limit);
            //result.rows = Mapper.Map<List<fz_sys_user>, List<fz_sys_userResultDTO>>(iquery.ToList());
            result.data = iquery.ToList();
            return result;
        }

        /// <summary>
        /// 记录登录密码错误次数
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int LoginErrorCount(AccountLoginDTO model, bool isSuccess = false)
        {
            bool result = false;
            int errorCount = 0;
            //获得用户
            var sysUser = _repository.GetModels(p => p.state == ZPFlagType.YES && p.account == model.Account).FirstOrDefault();
            //用户名或密码错误
            if (sysUser != null)
            {
                if (isSuccess)
                {
                    #region 登录成功
                    sysUser.errorTimes = 0;
                    sysUser.lastErrorTime = null;
                    #endregion
                }
                else
                {
                    #region 登录失败
                    if (sysUser.errorTimes.HasValue)
                    {
                        //判断是否超过最大错误次数
                        if (sysUser.errorTimes.Value >= ZPCommon.ZP_LOGIN_ERROR_MAX_COUNT)
                        {
                            errorCount = ZPCommon.ZP_LOGIN_ERROR_MAX_COUNT;
                        }
                        else
                        {
                            //错误次数+1
                            sysUser.errorTimes = sysUser.errorTimes.Value + 1;
                        }
                    }
                    else
                    {
                        sysUser.errorTimes = 1;
                    }
                    sysUser.lastErrorTime = DateTime.Now;
                    #endregion
                }
                result = _repository.Update(sysUser);
            }
            return errorCount;
        }

        /// <summary>
        /// 获得一个用户信息
        /// </summary>
        /// <returns></returns>
        public fz_sys_userResultDTO GetOne(string account)
        {
            fz_sys_userResultDTO result = null;
            using (var psie = (ZPJ_Entities)_repository.GetDbContext())
            {
                var iquery = from u in psie.fz_sys_user
                             join e in psie.fz_base_employee on u.employeeId equals (int)e.id
                             where u.state == ZPFlagType.YES && u.account == account
                             orderby u.id
                             select u;
                result = Mapper.Map<fz_sys_user, fz_sys_userResultDTO>(iquery.FirstOrDefault());
            }
            return result;
        }

        /// <summary>
        /// 保存用户-新增/修改
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="operate">1:重置用户密码</param>
        /// <returns></returns>
        public bool SaveSysUser(fz_sys_userOperateDTO dto, string operate)
        {
            bool result = false;
            using (var psie = (ZPJ_Entities)_repository.GetDbContext())
            {
                if (0 == dto.id || !dto.id.HasValue)
                {
                    //判断是否已经存在用户账号和员工
                    bool existsCount = psie.fz_sys_user.AsNoTracking().Any(p => p.state == ZPFlagType.YES && p.account == dto.account);
                    if (existsCount)
                    {
                        throw new Exception(TipsMessage.该用户账号已存在 + ",account:" + dto.account);
                    }

                    existsCount = psie.fz_sys_user.AsNoTracking().Where(p => p.state == ZPFlagType.YES && p.employeeId == dto.employeeId)
                    .GroupJoin(psie.fz_base_employee, u => u.employeeId, e => (int)e.id, (u, e) => new { u, e }).Any();
                    if (existsCount)
                    {
                        throw new Exception(TipsMessage.该员工已添加过账号 + ",account:" + dto.account);
                    }
                    //新增
                    var item = Mapper.Map<fz_sys_userOperateDTO, fz_sys_user>(dto);
                    item.password = ZPHelper.MD5Encrypt(ZPCommon.ZP_USER_DEFAULT_PASSWORD);
                    item.updater = dto.updater;
                    item.updatetime = DateTime.Now;
                    item.state = ZPFlagType.YES;
                    item.isLocked = (int)ZPUserLockedType.Normal;
                    //设置默认头像
                    item.headImg = "";
                    _repository.Add(item, false);
                    // 记录日志
                    //this.AddLog(psie, new LogData
                    //{
                    //    CurrentLogType = LogType.ADD,
                    //    LogDetails = "新增用户" + dto.account,
                    //    OpratorName = dto.updater
                    //});
                }
                else
                {
                    fz_sys_user item = _repository.Find(dto.id.Value);
                    //重置用户密码
                    if (operate == "1")
                    {
                        item.password = ZPHelper.MD5Encrypt("123456");
                    }
                    //解锁或锁定
                    else if (operate == "2")
                    {
                        if (dto.isLocked.HasValue)  //锁定/解锁功能
                        {
                            item.isLocked = dto.isLocked;
                            //超级管理员不能锁定
                            if (item.roleId != 1)
                            {
                                if (dto.isLocked.HasValue && dto.isLocked.Value == (int)ZPUserLockedType.Locked)
                                {
                                    item.lockTime = DateTime.Now;
                                }
                                else
                                {
                                    item.lockTime = null;
                                }
                            }
                            else
                            {
                                throw new Exception(TipsMessage.超级管理员不能被锁);
                            }
                        }
                    }
                    //密码错误达到最大值, 解锁
                    else if (operate == "3")
                    {
                        item.errorTimes = 0;
                        item.lastErrorTime = null;
                    }
                    else
                    {
                        //判断是否已经存在用户账号和员工
                        bool existsCount = psie.fz_sys_user.AsNoTracking().Any(p => p.state == ZPFlagType.YES && p.account == dto.account && p.id != dto.id);
                        if (existsCount)
                        {
                            throw new Exception(TipsMessage.该用户账号已存在);
                        }

                        existsCount = psie.fz_sys_user.Where(p => p.state == ZPFlagType.YES && p.account == dto.account && p.employeeId == dto.employeeId && p.id != dto.id)
                        .GroupJoin(psie.fz_base_employee, u => u.employeeId, e => (int)e.id, (u, e) => new { u, e }).Any();
                        if (existsCount)
                        {
                            throw new Exception(TipsMessage.该员工已添加过账号);
                        }

                        //修改
                        item.account = dto.account;
                        item.roleId = dto.roleId;
                        item.roleName = dto.roleName;
                        item.employeeId = dto.employeeId;
                        item.updatetime = DateTime.Now;
                    }
                    _repository.Update(item, false);

                    // 记录日志
                    //this.AddLog(psie, new LogData
                    //{
                    //    CurrentLogType = LogType.MODIFY,
                    //    LogDetails = "修改用户" + dto.account,
                    //    OpratorName = dto.updater
                    //});
                }
                result = _repository.SaveChanges();
            }
            return result;
        }

        /// <summary>
        /// 用户信息删除
        /// </summary>
        /// <returns></returns>
        public bool DeleteSysUser(List<fz_sys_userOperateDTO> dto, UserLoginDTO loginUser)
        {
            bool result = false;
            if (dto == null || dto.Count <= 0)
            {
                return result;
            }
            List<int> longIds = dto.Select(i => i.id.Value).ToList();
            //查询角色下是否还存在用户，存在则不能删除
            var users = _repository.GetModels(p => longIds.Contains(p.id));

            //删除用户
            //Delete(psie, users);
            int updateCount = users.Update(p => new fz_sys_user() { state = ZPFlagType.NO });
            if (updateCount > 0)
            {
                string strUserName = string.Join(",", users.Select(o => o.account).ToList());
                // 记录日志
                //this.AddLog(psie, new LogData
                //{
                //    CurrentLogType = LogType.DELETE,
                //    LogDetails = "删除用户" + strUserName,
                //    OpratorName = loginUser.account
                //});
            }
            result = updateCount > 0;
            return result;
        }

        #endregion

        #region 忘记密码
        /// <summary>
        /// 忘记密码-发送验证链接
        /// </summary>
        /// <returns></returns>
        public bool SendVerification(string account)
        {
            fz_sys_userResultDTO user = GetOne(account);
            if (user == null)
            {
                throw new Exception(TipsMessage.该用户不存在);
            }
            fz_base_employeeResultDTO employee = GetEmployee(account);
            if (string.IsNullOrWhiteSpace(employee.email))
            {
                throw new Exception(TipsMessage.该用户没有设置邮箱_请联系管理员);
            }

            string PSI_WebSite = ZPCommon.ZP_WebSite;
#if DEBUG
            PSI_WebSite = "http://localhost:1952";
#endif
            PSI_WebSite = PSI_WebSite + "/FZUser/SetPassword?sid=";
            DateTime now = DateTime.Now;
            string token = ZPCommon.ZP_FIND_PASSWORD_TOEKN;
            string vhref = string.Format("account={0}&time={1}&token={2}", account, now.ToString("yyyy-MM-dd HH:mm:ss"), token);
            vhref = ZPHelper.AesEncrypt(vhref, token); //加密处理
            string Subject = ZPCommon.ZP_FIND_PASSWORD_SUBJECT;
            string Body = string.Format(ZPCommon.ZP_FIND_PASSWORD_BODY, PSI_WebSite + vhref);
            List<string> emailAddressList = new List<string>();
            emailAddressList.Add(employee.email);
            bool result = ZPEmailHelper.SendEmail(Subject, Body, emailAddressList);
            if (result)
            {
                //保存验证链接到数据
                int updateCount = _repository.GetModels(p => p.id == user.id).Update(p => new fz_sys_user() { vLink = vhref });
            }
            return result;
        }

        /// <summary>
        /// 解码-忘记密码链接
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool FindPasswordDecrypt(string sid, out string account, out string errorMsg)
        {
            errorMsg = "";
            string vhref = ZPHelper.AesDecrypt(sid, ZPCommon.ZP_FIND_PASSWORD_TOEKN);
            List<string> prms = vhref.Split('&').ToList();
            account = "";
            string time = "";
            string token = "";
            foreach (string item in prms)
            {
                string key = item.Split('=')[0];
                string value = item.Split('=')[1];
                if (key == "account")
                    account = value;
                if (key == "time")
                    time = value;
                if (key == "token")
                    token = value;
            }
            if (string.IsNullOrWhiteSpace(account) || string.IsNullOrWhiteSpace(time) || string.IsNullOrWhiteSpace(token))
            {
                return false;
            }
            DateTime now = DateTime.Now;
            DateTime dt_time = DateTime.MinValue;
            if (!DateTime.TryParse(time, out dt_time))
            {
                return false;
            }
            TimeSpan cha = now - dt_time;
            //判断是否过期 超过24小时
            if (cha.TotalSeconds > (24 * 60 * 60))
            {
                errorMsg = "已经超过24小时，该链接已失效！";
                return false;
            }

            //判断链接是否已经使用过
            string ac = account;
            var user = _repository.Find(p => p.account == ac);
            if (user == null || user.vLink != sid)
            {
                errorMsg = "该链接已失效！";
                return false;
            }

            return true;
        }

        /// <summary>
        /// 保存新密码
        /// </summary>
        /// <returns></returns>
        public bool SavePassword(string account, string password)
        {
            bool result = false;
            using (var psie = (ZPJ_Entities)_fz_sys_userDAL.GetDbContext())
            {
                var iquery = from u in psie.fz_sys_user
                             join e in psie.fz_base_employee on u.employeeId equals (int)e.id
                             where u.account == account && u.state == ZPFlagType.YES
                             select u;

                if (iquery.Any())
                {
                    //更新密码
                    int updateCount = iquery.Update(p => new fz_sys_user()
                    {
                        password = ZPHelper.MD5Encrypt(password),
                        vLink = ""  //重置密码同时使链接失效
                    });
                    result = updateCount > 0;
                }
            }
            return result;
        }

        #endregion

        /// <summary>
        /// 保存修改的头像
        /// </summary>
        /// <returns></returns>
        public bool SaveAvatar(int id, string headImg)
        {
            bool result = false;
            //查询是否存在用户
            var iquery = _repository.GetModels(p => p.id == id);
            if (iquery.Any())
            {
                //更新头像
                int updateCount = iquery.Update(p => new fz_sys_user()
                {
                    headImg = headImg
                });
                result = _repository.SaveChanges();
            }
            return result;
        }
        /*
        /// <summary>
        /// 批量上传-系统用户账号
        /// </summary>
        /// <returns></returns>
        public bool UploadSysUser(string filepath, UserLoginDTO loginUser)
        {
            bool result = false;
            List<ImportSysUser> importList = new List<ImportSysUser>();
            using (var hce = SingleQueryObject.GetObj())
            {
                using (var tran = hce.Database.BeginTransaction())
                {
                    try
                    {
                        Stream fileStream = new MemoryStream(System.IO.File.ReadAllBytes(filepath));
                        List<string[]> colPro = new List<string[]>();
                        colPro.Add(new string[] { "员工编号", "account" });
                        colPro.Add(new string[] { "姓名", "name" });
                        colPro.Add(new string[] { "身份证", "idCard" });
                        colPro.Add(new string[] { "手机号", "mobile" });
                        colPro.Add(new string[] { "性别", "sex" });
                        colPro.Add(new string[] { "出生日期", "birthday" });
                        colPro.Add(new string[] { "住址", "address" });
                        colPro.Add(new string[] { "邮箱", "email" });
                        colPro.Add(new string[] { "员工类别", "type" });
                        colPro.Add(new string[] { "所在岗位", "roleName" });
                        colPro.Add(new string[] { "权限说明", "operateName" });

                        importList = ExcelHelper.Import<ImportSysUser>(fileStream, "Sheet1", colPro);
                        importList.RemoveAll(f => f == null);
                        importList.RemoveAll(f => f.account == null);
                        var arr_sys_menu = hce.tb_sys_menu.AsNoTracking().Where(p => p.state == ZPFlagType.YES).ToList();   //获得所有菜单信息
                        var roleList = hce.tb_sys_role.AsNoTracking().Where(p => p.state == ZPFlagType.YES).ToList();       //所有角色集合
                        #region 判断员工编号是否已经存在
                        List<string> arr_account = importList == null ? null : importList.Select(s => s.account).ToList();
                        if (arr_account != null)
                        {
                            var existsAccount = hce.fz_sys_user.AsNoTracking().Where(p => arr_account.Contains(p.account)).ToList();
                            if (existsAccount.Count > 0)
                            {
                                throw new Exception(string.Format("请检查员工编号:{0} 已存在!", string.Join(",", existsAccount.Select(s => s.account).ToList())));
                            }
                        }
                        #endregion

                        #region 判断要添加的岗位名称(角色名称)是否存在
                        List<string> arr_roleName = importList.Select(p => p.roleName).ToList();
                        List<string> arr_new_roleName = string.Join(",", arr_roleName).Replace("，", ",").Split(',').Where(p => p != "").ToList().Distinct().ToList();   //将xls中所有的权限名称集合
                        StringBuilder error_rolename = new StringBuilder();
                        arr_new_roleName.ForEach(s =>
                        {
                            if (!roleList.Any(p => p.name == s))
                            {
                                error_rolename.AppendFormat("{0},", s);
                            }
                        });
                        if (error_rolename.Length > 0)
                        {
                            throw new Exception(string.Format("请检查所在岗位:{0} 系统中不存在，请联系管理添加后再操作!", error_rolename.ToString()));
                        }
                        #endregion

                        //所有员工类别集合
                        var employeeTypeList = hce.tb_base_param.AsNoTracking().Where(p => p.type == ZPBaseType.EMPLOYEE_TYPE && p.state == ZPFlagType.YES).ToList();

                        List<string> zsgd = new List<string> { "新增", "编辑", "删除", "导入" };

                        List<fz_sys_menu> tmp_menuList = new List<fz_sys_menu>();
                        List<fz_sys_menu> tmp_btnList = new List<fz_sys_menu>();
                        List<int> arr_menuIds = new List<int>();
                        List<string> tmp_menuName = new List<string>();
                        List<string> tmp_btnName = new List<string>();

                        fz_base_paramOperateDTO fz_base_param = null;
                        fz_base_employeeOperateDTO tb_base_employeeoperate = null;
                        fz_sys_roleOperateDTO tb_sys_roleoperate = null;
                        fz_sys_userOperateDTO fz_sys_useroperate = null;
                        string menuIds = "";
                        string menuNames = "";
                        long ticks = 0;
                        importList.ForEach(s =>
                        {
                            #region 为空判断提示
                            if (string.IsNullOrWhiteSpace(s.account))
                            {
                                throw new Exception(string.Format("请检查有 员工编号 为空!"));
                            }
                            if (string.IsNullOrWhiteSpace(s.name))
                            {
                                throw new Exception(string.Format("请检查有 姓名 为空!"));
                            }
                            if (string.IsNullOrWhiteSpace(s.type))
                            {
                                throw new Exception(string.Format("请检查有 员工类别 为空!"));
                            }
                            if (string.IsNullOrWhiteSpace(s.roleName))
                            {
                                throw new Exception(string.Format("请检查有 所在岗位 为空!"));
                            }
                            #endregion

                            #region 1.添加员工类别，存在的不插入
                            var typeAny = employeeTypeList.Where(p => p.name == s.type).Any();
                            if (!typeAny)
                            {
                                fz_base_param = new fz_base_paramOperateDTO { name = s.type, type = Common.ZPBaseType.EMPLOYEE_TYPE, creater = loginUser.account };
                                _fz_base_paramServices.SaveBaseParam(fz_base_param, true);
                            }
                            #endregion

                            #region 2.添加员工信息，判断员工信息是否存在，存在的不插入
                            var tb_base_employee = hce.tb_base_employee.AsNoTracking().Where(p => p.name == s.account).Any();
                            if (!tb_base_employee)
                            {
                                tb_base_employeeoperate = new TB_Base_EmployeeOperateDTO
                                {
                                    name = s.name,
                                    code = s.account,
                                    idCard = s.idCard,
                                    mobile = s.mobile,
                                    sex = s.sex == "女" ? 0 : 1,
                                    birthday = s.birthday,
                                    address = s.address,
                                    email = s.email,
                                    type = s.type,
                                    updater = loginUser.account
                                };
                                _TB_Base_EmployeeServices.SaveBaseEmployee(tb_base_employeeoperate, true);
                            }
                            #endregion

                            #region 3.权限说明，增删改查导都分配，如果有值则按照内容分配
                            tmp_menuName = s.roleName.Replace("，", ",").Split(',').ToList().Distinct().ToList();
                            if (string.IsNullOrWhiteSpace(s.operateName))
                            {
                                s.operateName = string.Join(",", zsgd);
                            }
                            tmp_btnName = s.operateName.Replace("，", ",").Split(',').ToList().Distinct().ToList();

                            //1.根据xls岗位名称获得角色对应的权限(系统中提前建立好角色所有的权限包含增删改查导)
                            menuIds = string.Join(",", roleList.Where(p => tmp_menuName.Contains(p.name)).Select(o => o.menuIds).ToList());
                            arr_menuIds = Array.ConvertAll(menuIds.Split(',').Where(p => p != "").ToArray(), int.Parse).ToList();
                            //menuNames = string.Join(",", roleList.Where(p => tmp_menuName.Contains(p.name)).Select(o => o.menuNames).ToList());
                            //2.根据权限id查询权限对象集合
                            tmp_menuList = arr_sys_menu.Where(p => arr_menuIds.Contains(p.id)).ToList();
                            //3.根据xls的权限筛选增删改查导
                            tmp_btnList = tmp_menuList.Where(p => zsgd.Contains(p.name)).ToList();
                            //4.获得新的权限id和name
                            tmp_menuList.RemoveAll(it => tmp_btnList.Contains(it)); //去掉 增删改查 按钮权限
                            tmp_btnList = tmp_btnList.Where(p => tmp_btnName.Contains(p.name)).ToList();    //筛选出按钮权限

                            menuIds = string.Join(",", tmp_menuList.Select(p => p.id).ToList()) + "," + string.Join(",", tmp_btnList.Select(p => p.id).ToList());       //拼装菜单和按钮权限id
                            menuNames = string.Join(",", tmp_menuList.Select(p => p.name).ToList()) + "," + string.Join(",", tmp_btnList.Select(p => p.name).ToList()); //拼装菜单和按钮权限name

                            if (roleList.Where(p => p.menuIds == menuIds).Any())
                            {
                                tb_sys_roleoperate = Mapper.Map<DTO.TB_Sys_Role.TB_Sys_RoleOperateDTO>(roleList.Where(p => p.menuIds == menuIds).FirstOrDefault());
                            }
                            else
                            {
                                //5.增加角色信息
                                ticks = DateTime.Now.Ticks;
                                tb_sys_roleoperate = new DTO.TB_Sys_Role.TB_Sys_RoleOperateDTO { name = "导入角色" + ticks, code = ticks.ToString(), menuIds = menuIds, menuNames = menuNames, updater = loginUser.account };
                                _TB_Sys_RoleServices.SaveSysRole(tb_sys_roleoperate);
                                roleList = hce.tb_sys_role.AsNoTracking().Where(p => p.state == ZPFlagType.YES).ToList();       //重新获得所有角色集合
                            }
                            #endregion

                            #region 4.添加用户账号
                            fz_sys_useroperate = new fz_sys_userOperateDTO { account = s.account, employeeId = tb_base_employeeoperate.id, roleId = tb_sys_roleoperate.id, roleName = tb_sys_roleoperate.name, updater = loginUser.account };
                            SaveSysUser(fz_sys_useroperate, "");
                            #endregion
                        });

                        int addCount = hce.SaveChanges();
                        result = addCount > 0;
                        tran.Commit();
                        result = true;
                    }
                    catch (DbEntityValidationException dbEx)
                    {
                        string errorMsg = "";
                        foreach (var validationErrors in dbEx.EntityValidationErrors)
                        {
                            foreach (var validationError in validationErrors.ValidationErrors)
                            {
                                errorMsg += string.Format("属性:{0},错误:{1};", validationError.PropertyName, validationError.ErrorMessage);
                            }
                        }
                        tran.Rollback();
                        throw new Exception(errorMsg); //抛到Controller层
                    }
                    catch (Exception e)
                    {
                        tran.Rollback();
                        throw new Exception(e.Message); //抛到Controller层
                    }
                    finally
                    {
                        if (File.Exists(filepath))
                            File.Delete(filepath);
                    }
                }
            }
            return result;
        }
        */
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public UserLoginDTO Login(AccountLoginDTO model)
        {
            UserLoginDTO result = new UserLoginDTO();
            //var psie = SingleQueryObject.GetObj();
            //获得用户
            var md5Passwrod = ZP.Common.ZPHelper.MD5Encrypt(model.Password);
            var sysUser = _repository.Find(p => p.state == ZPFlagType.YES && p.account == model.Account && p.password == md5Passwrod);
            //用户名或密码错误
            if (sysUser == null)
            {
                return null;
            }
            //账号被锁定
            if (sysUser.isLocked.HasValue && sysUser.isLocked.Value == (int)ZPUserLockedType.Locked)
            {
                result.isLocked = sysUser.isLocked.Value;
                return result;
            }
            //账号被停用
            if (sysUser.state == ZPFlagType.NO)
            {
                result.state = sysUser.state;
                return result;
            }

            result = Mapper.Map<UserLoginDTO>(sysUser);
            //查询对应员工信息
            fz_base_employee employee = _fz_base_employeeDAL.Find(p => p.id == result.employeeId);
            result.employee = Mapper.Map<fz_base_employee, fz_base_employeeResultDTO>(employee);
            List<fz_sys_menu> sysMenuList = null;
            //判断角色
            if (result.roleId == 1)  //超级管理员
            {
                //获得所有菜单
                sysMenuList = _fz_sys_menuDAL.GetModels(p => p.state == ZPFlagType.YES).ToList();
            }
            else
            {
                //查询角色菜单ID集合
                fz_sys_role sysRole = _fz_sys_roleDAL.Find(p => p.id == result.roleId);
                List<string> menuIds = null;
                if (null != sysRole)
                {
                    //查询对应的菜单
                    menuIds = sysRole.menuIds.Split(',').ToList();
                    sysMenuList = _fz_sys_menuDAL.GetModels(p => menuIds.Contains(p.id.ToString())).ToList();

                    //根据子菜单查询父节点菜单
                    var parentIds = sysMenuList.Select(s => s.upId).ToList();
                    if (_fz_sys_menuDAL.GetModels(p => parentIds.Contains(p.id)).Any())
                    {
                        sysMenuList.AddRange(_fz_sys_menuDAL.GetModels(p => parentIds.Contains(p.id)).ToList());
                        sysMenuList = sysMenuList.Distinct().ToList();  //去重
                    }
                }
            }
            //fz_sys_menu转CurrentUserAuthority
            result.CurrentUserAuthorityList = Mapper.Map<List<CurrentUserAuthority>>(sysMenuList);
            return result;
        }

        /// <summary>
        /// 根据 account 获得后台账号
        /// </summary>
        /// <returns></returns>
        public fz_base_employeeResultDTO GetEmployee(string account)
        {
            fz_base_employeeResultDTO result = null;
            using (var ef = (ZPJ_Entities)_fz_sys_userDAL.GetDbContext())
            {
                var iquery = from u in ef.fz_sys_user
                             join e in ef.fz_base_employee on u.employeeId equals (int)e.id
                             where u.account == account && u.state == ZPFlagType.YES
                             orderby u.id
                             select e;
                result = Mapper.Map<fz_base_employee, fz_base_employeeResultDTO>(iquery.FirstOrDefault());
            }
            return result;
        }

        public fz_sys_userResultDTO GetUser(int id)
        {
            return Mapper.Map<fz_sys_userResultDTO>(_repository.Find(p => p.id == id));
        }
    }
}
